<template>
    <div class="sale-count-page">
        <!-- 顶部筛选 -->
        <el-card class="filter-card" shadow="never">
            <div class="quick-tabs">
                <el-radio-group v-model="activeDateTab" size="large" @change="handleDateTabChange">
                    <el-radio-button v-for="item in quickDateTabs" :key="item.value" :label="item.value">
                        {{ item.label }}
                    </el-radio-button>
                </el-radio-group>
            </div>
            <el-form :model="queryForm" :inline="true" label-width="90px" class="filter-form">
                <el-form-item label="销售单号">
                    <el-input v-model="queryForm.saleOrderNo" placeholder="请输入销售单号" clearable />
                </el-form-item>
                <el-form-item label="客户名称">
                    <el-input v-model="queryForm.customerName" placeholder="请输入客户名称" clearable />
                </el-form-item>
                <el-form-item label="销售负责人">
                    <el-input v-model="queryForm.salesUser" placeholder="请输入销售负责人" clearable />
                </el-form-item>
                <el-form-item label="销售部门">
                    <el-input v-model="queryForm.salesDepartment" placeholder="请输入销售部门" clearable />
                </el-form-item>
                <el-form-item label="销售日期">
                    <el-date-picker v-model="queryForm.dateRange" type="daterange" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled="activeDateTab !== 'custom'"
                        style="width: 260px" @change="handleCustomDateChange" />
                </el-form-item>
                <el-form-item>
                    <el-space>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-space>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 中部统计卡片 -->
        <el-row :gutter="16" class="stat-row">
            <el-col :span="8">
                <el-card class="stat-card amount-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <Coin />
                        </el-icon>
                        <span>销售订单总金额</span>
                    </div>
                    <div class="stat-value">¥{{ formatAmount(statistics.totalAmount) }}</div>
                    <div class="stat-desc">按当前筛选条件统计</div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="stat-card customer-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <UserFilled />
                        </el-icon>
                        <span>客户数量</span>
                    </div>
                    <div class="stat-value">{{ statistics.customerCount }}</div>
                    <div class="stat-desc">参与下单的客户数</div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="stat-card order-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <List />
                        </el-icon>
                        <span>销售订单数量</span>
                    </div>
                    <div class="stat-value">{{ statistics.orderCount }}</div>
                    <div class="stat-desc">合计销售单数量</div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 底部表格 -->
        <el-card class="table-card" shadow="never">
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <el-button type="primary" text @click="handleExport">
                        <el-icon class="toolbar-icon">
                            <Download />
                        </el-icon>
                        导出
                    </el-button>
                    <el-button text @click="fetchSaleCount">
                        <el-icon class="toolbar-icon">
                            <RefreshRight />
                        </el-icon>
                        刷新
                    </el-button>
                </div>
                <div class="toolbar-right">
                    共 {{ page.listCount }} 条记录
                </div>
            </div>

            <el-scrollbar x>
                <el-table v-loading="loading" :data="tableRows" border stripe style="min-width: 1200px"
                    :span-method="tableSpanMethod" size="large">
                    <el-table-column label="序号" width="60" fixed="left" align="center">
                        <template #default="{ row }">
                            {{ getOrderIndex(row) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="saleOrderNo" label="销售单号" width="160" fixed="left" align="center">
                        <template #default="{ row }">
                            <el-link type="primary" @click="handleShowDetail(row)">
                                {{ row.saleOrderNo || '-' }}
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="saleOrderDate" label="销售日期" width="140" align="center">
                        <template #default="{ row }">
                            {{ formatDate(row.saleOrderDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="customerName" label="客户名称" min-width="160" show-overflow-tooltip
                        align="center" />
                    <el-table-column prop="salesDepartment" label="销售部门" min-width="150" show-overflow-tooltip
                        align="center" />
                    <el-table-column prop="salesUser" label="销售负责人" width="130" show-overflow-tooltip align="center" />
                    <el-table-column label="货品名称" min-width="160" show-overflow-tooltip align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.productName || row.productName || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="货品编号" min-width="140" show-overflow-tooltip align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.productCode || row.productCode || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="销售数量" width="110" align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.quantity ?? row.quantity ?? 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="销售金额" width="130" align="center">
                        <template #default="{ row }">
                            ¥{{ formatAmount(row.productDetail?.amount ?? row.amount ?? 0) }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-scrollbar>

            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
                    layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20, 30, 50]"
                    :total="page.listCount" @current-change="handlePageChange" @size-change="handleSizeChange" />
            </div>
        </el-card>

        <!-- 详情抽屉 -->
        <el-drawer v-model="detailVisible" size="80%" :with-header="false">
            <div class="detail-wrapper" v-loading="detailLoading">
                <div class="detail-header">
                    <div class="detail-title">
                        <div>
                            <div class="order-no">销售单号：{{ detailBase.saleOrderNo || '--' }}</div>
                            <div class="detail-sub">
                                销售日期：{{ formatDate(detailBase.saleOrderDate) }} ｜ 单据状态：
                                <el-tag size="small">{{ detailBase.orderStatus || '——' }}</el-tag>
                            </div>
                        </div>
                        <div class="detail-actions">
                            <el-button v-for="btn in detailActionButtons" :key="btn" size="small"
                                :disabled="btn !== '打印'">
                                {{ btn }}
                            </el-button>
                        </div>
                    </div>
                </div>
                <el-card shadow="never" class="detail-card base-card">
                    <el-descriptions :column="4" border size="small" label-class-name="base-label">
                        <el-descriptions-item label="制单人">
                            {{ detailBase.makerName || detailBase.salesUser || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="制单时间">
                            {{ detailBase.madeTime ? formatDateTime(detailBase.madeTime) : '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="所在部门">
                            {{ detailBase.salesDepartment || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="来源部门">
                            {{ detailBase.sourceDepartment || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="送货日期">
                            {{ detailBase.deliveryDate ? formatDate(detailBase.deliveryDate) : '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="客户名称">
                            {{ detailBase.customerName || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系人">
                            {{ detailBase.contactName || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系方式">
                            {{ detailBase.contactPhone || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="销售部门">
                            {{ detailBase.salesDepartment || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="销售负责人">
                            {{ detailBase.salesUser || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="备注" :span="2">
                            {{ detailBase.remark || '-' }}
                        </el-descriptions-item>
                    </el-descriptions>
                </el-card>

                <el-card shadow="never" class="detail-card tabs-card">
                    <el-tabs v-model="detailActiveTab" type="border-card">
                        <el-tab-pane label="其他信息" name="info">
                            <div class="info-section">
                                <div class="info-block">
                                    <div class="info-title">附件</div>
                                    <div v-if="detailExtras.attachments.length" class="attachment-list">
                                        <el-link v-for="file in detailExtras.attachments" :key="file.name"
                                            type="success" :underline="false">
                                            {{ file.name }}
                                        </el-link>
                                    </div>
                                    <el-empty v-else description="暂无附件" :image-size="80" />
                                </div>
                                <div class="info-block">
                                    <div class="info-title">自定义字段</div>
                                    <div v-if="detailExtras.customFields.length" class="custom-grid">
                                        <div v-for="field in detailExtras.customFields" :key="field.label"
                                            class="custom-item">
                                            <span class="label">{{ field.label }}</span>
                                            <span class="value">{{ field.value || '-' }}</span>
                                        </div>
                                    </div>
                                    <el-empty v-else description="暂无自定义字段" :image-size="80" />
                                </div>
                            </div>
                        </el-tab-pane>

                        <el-tab-pane label="销售明细" name="goods">
                            <el-table :data="detailGoods" border stripe style="width: 100%">
                                <el-table-column type="index" width="60" label="序号" align="center" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="specificationModel" label="规格" min-width="120"
                                    show-overflow-tooltip align="center" />
                                <el-table-column prop="unitName" label="单位" width="90" align="center" />
                                <el-table-column prop="quantity" label="数量" width="110" align="center" />
                                <el-table-column prop="price" label="单价" width="110" align="center">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.price) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="amount" label="金额" width="130" align="center">
                                    <template #default="{ row }">
                                        <span class="amount-text">¥{{ formatAmount(row.amount) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip
                                    align="center" />
                            </el-table>
                            <div class="detail-summary" v-if="detailGoods.length">
                                <span>货品种类：{{ detailGoods.length }}</span>
                                <span>总数量：{{ detailGoodsQuantity }}</span>
                                <span>总金额：¥{{ formatAmount(detailGoodsAmount) }}</span>
                            </div>
                            <el-empty v-else description="暂无销售明细" :image-size="100" />
                        </el-tab-pane>

                        <el-tab-pane label="出库记录" name="outbound">
                            <el-table :data="detailLists.outbound" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="deliveryNo" label="出库单号" min-width="160" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="warehouseName" label="仓库" min-width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="deliveryDate" label="出库日期" width="160" align="center">
                                    <template #default="{ row }">
                                        {{ formatDate(row.deliveryDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="deliveryProducts" label="出库货品" min-width="200"
                                    show-overflow-tooltip align="center" />
                                <el-table-column prop="quantity" label="数量" width="90" align="center" />
                                <el-table-column prop="amount" label="金额" width="120" align="center">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.amount) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="经办人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="documentCreator" label="制单人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="documentCreation" label="制单时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ row.documentCreation ? formatDateTime(row.documentCreation) : '-' }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.outbound.length" description="暂无出库记录" :image-size="80" />
                        </el-tab-pane>

                        <el-tab-pane label="退货记录" name="returns">
                            <el-table :data="detailLists.returns" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="quantity" label="退货数量" width="110" align="center" />
                                <el-table-column prop="reason" label="退货原因" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="operator" label="操作人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="退货时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.returns.length" description="暂无退货记录" :image-size="80" />
                        </el-tab-pane>

                        <el-tab-pane label="操作记录" name="operations">
                            <el-table :data="detailLists.operations" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="operationType" label="操作类型" min-width="150" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="operator" label="操作人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="操作时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.operations.length" description="暂无操作记录" :image-size="80" />
                        </el-tab-pane>

                        <el-tab-pane label="审核记录" name="approvals">
                            <el-table :data="detailLists.approvals" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="statusName" label="审核状态" width="140" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="row.status === 1 ? 'success' : 'info'">
                                            {{ row.statusName || row.status || '—' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approver" label="审核人" width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="remark" label="意见" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="审核时间" width="200" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.approvals.length" description="暂无审核记录" :image-size="80" />
                        </el-tab-pane>
                    </el-tabs>
                </el-card>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Coin, UserFilled, List, RefreshRight, Download } from '@element-plus/icons-vue'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

type QuickDateTab = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth' | 'custom'

interface SaleCountProduct {
    productName?: string
    productCode?: string
    specificationModel?: string
    unitName?: string
    quantity?: number
    amount?: number
    price?: number
    remark?: string
}

interface SaleCountRecord {
    saleOrderId?: number | string
    saleOrderNo?: string
    saleOrderDate?: string
    customerName?: string
    salesDepartment?: string
    salesUser?: string
    productName?: string
    productCode?: string
    specification?: string
    quantity?: number
    amount?: number
    price?: number
    remark?: string
    contactName?: string
    contactPhone?: string
    orderStatus?: string | number
    productDetails?: SaleCountProduct[]
    saleDetails?: SaleCountProduct[]
    detailList?: SaleCountProduct[]
    details?: SaleCountProduct[]
    [key: string]: any
}

interface SaleCountRow extends SaleCountRecord {
    detailIndex: number
    detailCount: number
    orderIndex: number
    productDetail: SaleCountProduct | null
}

interface AttachmentItem {
    name: string
    url?: string
}

interface CustomFieldItem {
    label: string
    value?: string
}

const quickDateTabs: Array<{ label: string, value: QuickDateTab }> = [
    { label: '今日', value: 'today' },
    { label: '昨日', value: 'yesterday' },
    { label: '本周', value: 'thisWeek' },
    { label: '上周', value: 'lastWeek' },
    { label: '本月', value: 'thisMonth' },
    { label: '上月', value: 'lastMonth' },
    { label: '自定义时间', value: 'custom' }
]

const activeDateTab = ref<QuickDateTab>('today')

const queryForm = reactive({
    saleOrderNo: '',
    customerName: '',
    salesUser: '',
    salesDepartment: '',
    dateRange: [] as string[]
})

const statistics = reactive({
    totalAmount: 0,
    customerCount: 0,
    orderCount: 0
})

const page = reactive({
    pageindex: 1,
    pagesize: 5,
    pageCount: 0,
    listCount: 0
})

const loading = ref(false)
const tableRows = ref<SaleCountRow[]>([])
const rawRecords = ref<SaleCountRecord[]>([])

const detailVisible = ref(false)
const detailLoading = ref(false)
const detailActionButtons = ['编辑', '删除', '审核', '关闭', '复制', '打印']
const detailActiveTab = ref('info')
const detailBase = reactive<Record<string, any>>({
    saleOrderNo: '',
    saleOrderDate: '',
    customerName: '',
    salesDepartment: '',
    salesUser: '',
    contactName: '',
    contactPhone: '',
    remark: '',
    orderStatus: '',
    makerName: '',
    madeTime: '',
    sourceDepartment: '',
    deliveryDate: ''
})
const detailGoods = ref<SaleCountProduct[]>([])
const detailExtras = reactive({
    attachments: [] as AttachmentItem[],
    customFields: [] as CustomFieldItem[]
})
const detailLists = reactive({
    outbound: [] as Array<Record<string, any>>,
    returns: [] as Array<Record<string, any>>,
    operations: [] as Array<Record<string, any>>,
    approvals: [] as Array<Record<string, any>>
})

const detailGoodsQuantity = computed(() => {
    return detailGoods.value.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const detailGoodsAmount = computed(() => {
    return detailGoods.value.reduce((sum, item) => sum + (item.amount || 0), 0)
})

const applyQuickRange = (tab: QuickDateTab) => {
    if (tab === 'custom') {
        if (!queryForm.dateRange || queryForm.dateRange.length !== 2) {
            queryForm.dateRange = []
        }
        return
    }
    const [start, end] = getQuickRange(tab)
    queryForm.dateRange = [start, end]
}

const getQuickRange = (tab: QuickDateTab): [string, string] => {
    const today = moment()
    switch (tab) {
        case 'today':
            return [today.clone().startOf('day').format('YYYY-MM-DD'), today.clone().endOf('day').format('YYYY-MM-DD')]
        case 'yesterday': {
            const y = today.clone().subtract(1, 'day')
            return [y.startOf('day').format('YYYY-MM-DD'), y.endOf('day').format('YYYY-MM-DD')]
        }
        case 'thisWeek':
            return [today.clone().startOf('week').format('YYYY-MM-DD'), today.clone().endOf('week').format('YYYY-MM-DD')]
        case 'lastWeek': {
            const last = today.clone().subtract(1, 'week')
            return [last.startOf('week').format('YYYY-MM-DD'), last.endOf('week').format('YYYY-MM-DD')]
        }
        case 'thisMonth':
            return [today.clone().startOf('month').format('YYYY-MM-DD'), today.clone().endOf('month').format('YYYY-MM-DD')]
        case 'lastMonth': {
            const lastMonth = today.clone().subtract(1, 'month')
            return [lastMonth.startOf('month').format('YYYY-MM-DD'), lastMonth.endOf('month').format('YYYY-MM-DD')]
        }
        default:
            return ['', '']
    }
}

const handleDateTabChange = (value: QuickDateTab) => {
    activeDateTab.value = value
    applyQuickRange(value)
    if (value !== 'custom') {
        page.pageindex = 1
        fetchSaleCount()
    }
}

const handleCustomDateChange = () => {
    activeDateTab.value = 'custom'
}

const handleQuery = () => {
    page.pageindex = 1
    fetchSaleCount()
}

const handleReset = () => {
    queryForm.saleOrderNo = ''
    queryForm.customerName = ''
    queryForm.salesUser = ''
    queryForm.salesDepartment = ''
    activeDateTab.value = 'today'
    applyQuickRange('today')
    page.pageindex = 1
    fetchSaleCount()
}

const handlePageChange = (pageindex: number) => {
    page.pageindex = pageindex
    fetchSaleCount()
}

const handleSizeChange = (size: number) => {
    page.pagesize = size
    page.pageindex = 1
    fetchSaleCount()
}

const normalizeSaleRecord = (record: SaleCountRecord): SaleCountRecord => {
    const aliases = {
        saleOrderNo: record.saleOrderNo || record.salesOrderNo || record.orderNo || record.orderCode,
        saleOrderDate: record.saleOrderDate || record.salesOrderDate || record.orderDate || record.createdTime,
        customerName: record.customerName || record.clientName || record.customer || record.buyerName,
        salesDepartment: record.salesDepartment || record.department || record.salesDeptName,
        salesUser: record.salesUser || record.salesman || record.salesUserName || record.handler,
        orderStatus: record.orderStatus || record.statusName || record.saleOrderStatus || record.salesStatus,
        makerName: record.makerName || record.createdBy || record.salesUser,
        madeTime: record.madeTime || record.salesOrderTime || record.salesOrderDateTime || record.createdTime,
        productName: record.productName || record.goodsName,
        productCode: record.productCode || record.goodsCode,
        quantity: record.quantity ?? record.saleQuantity ?? record.salesQuantity,
        amount: record.amount ?? record.saleAmount ?? record.salesAmount,
        price: record.price ?? record.salePrice ?? record.unitPrice,
        remark: record.remark || record.memo || record.note
    }

    const contactName =
        record.contactName ||
        record.salesContact ||
        record.contact ||
        record.customerContact ||
        record.buyerContact ||
        record.linkMan ||
        record.linkman ||
        record.contacts
    const contactPhone =
        record.contactPhone ||
        record.salesContactPhone ||
        record.contactWay ||
        record.contactPhoneNumber ||
        record.contactTel ||
        record.contactMobile ||
        record.customerPhone ||
        record.buyerPhone

    return {
        ...record,
        ...aliases,
        contactName,
        contactPhone
    }
}

const normalizeProductList = (record: SaleCountRecord): SaleCountProduct[] => {
    const candidateLists = [
        record.saleDetails,
        record.productDetails,
        record.detailList,
        record.details,
        (record as any).products
    ]

    for (const list of candidateLists) {
        if (Array.isArray(list) && list.length > 0) {
            return list.map(item => ({
                productName: item.productName || item.goodsName || '--',
                productCode: item.productCode || item.goodsCode || '--',
                specificationModel: item.specificationModel || item.specification || item.productSpecification || '',
                unitName: item.unitName || item.unit || '',
                quantity: Number(item.quantity ?? item.saleQuantity ?? item.salesQuantity ?? 0),
                amount: Number(item.amount ?? item.saleAmount ?? item.salesAmount ?? 0),
                price: Number(item.price ?? item.unitPrice ?? 0),
                remark: item.remark || ''
            }))
        }
    }

    if (record.productName || record.productCode) {
        return [{
            productName: record.productName || '--',
            productCode: record.productCode || '--',
            specificationModel: record.specification || record.specificationModel || '',
            unitName: record.unitName || record.unit || '',
            quantity: Number(record.quantity ?? 0),
            amount: Number(record.amount ?? 0),
            price: Number(record.price ?? record.amount ?? 0),
            remark: record.remark || ''
        }]
    }

    return []
}

const flattenRecords = (records: SaleCountRecord[]): SaleCountRow[] => {
    const rows: SaleCountRow[] = []
    records.forEach((record, orderIndex) => {
        const productList = normalizeProductList(record)
        if (productList.length === 0) {
            rows.push({
                ...record,
                detailIndex: 0,
                detailCount: 1,
                orderIndex,
                productDetail: null
            })
            return
        }
        productList.forEach((detail, index) => {
            rows.push({
                ...record,
                detailIndex: index,
                detailCount: productList.length,
                orderIndex,
                productDetail: detail
            })
        })
    })
    return rows
}

const buildGroupedRecords = (list: SaleCountRecord[]): SaleCountRecord[] => {
    if (!list || list.length === 0) return []
    const map = new Map<string, SaleCountRecord & { details: SaleCountProduct[] }>()

    list.forEach((item, index) => {
        const key = item.saleOrderNo || `unknown_${index}`
        if (!map.has(key)) {
            map.set(key, {
                ...item,
                details: []
            })
        }
        const target = map.get(key)!
        const productList = normalizeProductList(item)
        if (productList.length > 0) {
            target.details?.push(...productList)
        } else if (item.productName || item.productCode) {
            const detail: SaleCountProduct = {
                productName: item.productName || '--',
                productCode: item.productCode || '--',
                specificationModel: item.specificationModel || item.specification || '',
                unitName: item.unitName || item.unit || '',
                quantity: Number(item.quantity ?? 0),
                amount: Number(item.amount ?? 0),
                price: Number(item.price ?? 0),
                remark: item.remark || ''
            }
            target.details?.push(detail)
        }
    })

    return Array.from(map.values())
}

const fetchSaleCount = async () => {
    loading.value = true
    try {
        const params: Record<string, any> = {
            salesOrderNo: queryForm.saleOrderNo || undefined,
            saleOrderNo: queryForm.saleOrderNo || undefined,
            customerName: queryForm.customerName || undefined,
            salesUser: queryForm.salesUser || undefined,
            salesDepartment: queryForm.salesDepartment || undefined,
            beginDate: queryForm.dateRange?.[0],
            endDate: queryForm.dateRange?.[1],
            pageindex: page.pageindex,
            pagesize: page.pagesize
        }

        const res = await myaxios.get('/api/Statis/GetSaleCount', { params })
        const result = res.data?.data || {}
        const pages = result.pages || {}
        const orderList: SaleCountRecord[] = pages.data || result.data || result.list || []
        const normalizedList = orderList.map(normalizeSaleRecord)
        const groupedOrders = buildGroupedRecords(normalizedList)

        statistics.totalAmount = Number(result.totalAmount ?? result.statistical?.totalAmount ?? 0)
        statistics.customerCount = Number(result.customerCount ?? result.statistical?.customerCount ?? 0)
        statistics.orderCount = Number(result.orderCount ?? result.statistical?.orderCount ?? groupedOrders.length)

        page.listCount = Number(pages.listCount ?? result.listCount ?? groupedOrders.length)
        page.pageCount = Number(pages.pageCount ?? result.pageCount ?? Math.ceil(page.listCount / page.pagesize))

        rawRecords.value = groupedOrders
        tableRows.value = flattenRecords(groupedOrders)
    } catch (error) {
        console.error('获取销售统计失败', error)
        ElMessage.error('获取销售统计数据失败')
    } finally {
        loading.value = false
    }
}

const resetDetailData = () => {
    detailActiveTab.value = 'info'
    detailGoods.value = []
    detailExtras.attachments = []
    detailExtras.customFields = []
    detailLists.outbound = []
    detailLists.returns = []
    detailLists.operations = []
    detailLists.approvals = []
}

const fillDetailBaseInfo = (record: SaleCountRecord) => {
    detailBase.saleOrderNo = record.saleOrderNo || ''
    detailBase.saleOrderDate = record.saleOrderDate || ''
    detailBase.customerName = record.customerName || ''
    detailBase.salesDepartment = record.salesDepartment || ''
    detailBase.salesUser = record.salesUser || ''
    detailBase.contactName =
        record.contactName ||
        record.salesContact ||
        record.contact ||
        record.customerContact ||
        record.buyerContact ||
        record.linkMan ||
        record.linkman ||
        record.contacts ||
        ''
    detailBase.contactPhone =
        record.contactPhone ||
        record.salesContactPhone ||
        record.contactWay ||
        record.contactPhoneNumber ||
        record.contactTel ||
        record.contactMobile ||
        record.customerPhone ||
        record.buyerPhone ||
        ''
    detailBase.remark = record.remark || ''
    detailBase.orderStatus = record.orderStatus || record.statusName || record.saleOrderStatus || ''
    detailBase.makerName = record.makerName || record.createdBy || record.salesUser || ''
    detailBase.madeTime = record.madeTime || record.createdTime || ''
    detailBase.sourceDepartment = record.sourceDepartment || record.originDepartment || ''
    detailBase.deliveryDate = record.deliveryDate || record.outboundDate || ''
}

const normalizeRecordList = (list: any, mapper: (item: any) => any) => {
    if (Array.isArray(list)) {
        return list.map(mapper)
    }
    return []
}

const normalizeAttachments = (record: any): AttachmentItem[] => {
    const list = record?.attachments || record?.files || record?.fileList
    if (Array.isArray(list)) {
        return list.map((item: any, index: number) => ({
            name: item.name || item.fileName || `附件${index + 1}`,
            url: item.url || item.fileUrl
        }))
    }
    return []
}

const normalizeCustomFields = (record: any): CustomFieldItem[] => {
    const fields = record?.customFields
    if (Array.isArray(fields)) {
        return fields.map((item: any, index: number) => ({
            label: item.label || item.fieldName || `自定义字段${index + 1}`,
            value: item.value || item.fieldValue
        }))
    }
    const fallbackKeys = ['customField1', 'customField2', 'customField3', 'customField4', 'customField5']
    const fallback: CustomFieldItem[] = []
    fallbackKeys.forEach((key, index) => {
        if (record && record[key] !== undefined) {
            fallback.push({
                label: `自定义字段${index + 1}`,
                value: record[key]
            })
        }
    })
    return fallback
}

const normalizeSaleDeliveryRecords = (records: any): Array<Record<string, any>> => {
    if (!Array.isArray(records)) return []
    return records.map((item: any) => ({
        deliveryNo: item.outboundCode || item.deliveryNo || item.stockoutNo || item.warehouseDeliveryNo || '--',
        deliveryDate: item.outboundDate || item.deliveryDate || item.createdTime || '',
        warehouseName: item.warehouseName || item.storehouseName || '-',
        deliveryProducts: item.outboundNames || item.deliveryProducts || item.productNames || item.goodsName || '-',
        quantity: Number(item.outboundNum ?? item.quantity ?? item.totalQty ?? 0),
        unitName: item.outboundUnitName || item.unitName || item.unit || '',
        amount: Number(item.outboundPrice ?? item.amount ?? item.totalAmount ?? 0),
        operator: item.handlerProple || item.handler || item.operator || item.userName || '-',
        documentCreator: item.documentCreator || item.creator || item.createdBy || '',
        documentCreation: item.documentCreation || item.docTime || item.documentTime || item.createdTime || ''
    }))
}

const fillDetailLists = (record: any) => {
    const outboundSource = record?.outboundRecords || record?.deliveryList
    detailLists.outbound = normalizeSaleDeliveryRecords(outboundSource)

    detailLists.returns = normalizeRecordList(record?.returnRecords || record?.salesReturnList, (item: any) => ({
        productName: item.productName || item.goodsName || '-',
        quantity: Number(item.quantity ?? 0),
        reason: item.reason || item.remark || '',
        operator: item.operator || item.userName || '-',
        time: item.returnTime || item.createdTime || ''
    }))

    detailLists.operations = normalizeRecordList(record?.operationRecords || record?.operationList, (item: any) => ({
        operationType: item.operationType || item.action || '-',
        operator: item.operator || item.userName || '-',
        remark: item.remark || '',
        time: item.operationTime || item.createdTime || ''
    }))

    detailLists.approvals = normalizeRecordList(record?.approvalRecords || record?.approvalList, (item: any) => ({
        status: item.status ?? item.approvalStatus,
        statusName: item.statusName || item.approvalStatusName || '',
        approver: item.approver || item.userName || '-',
        remark: item.remark || '',
        time: item.approvalTime || item.createdTime || ''
    }))
}

const fetchSaleDeliveryRecords = async (saleOrderNo?: string) => {
    if (!saleOrderNo) return []
    const params = { salesOrderNo: saleOrderNo }
    const res = await myaxios.get('/api/Statis/GetSaleDeliveryRecords', { params })
    const payload = res.data?.data ?? res.data ?? []
    return normalizeSaleDeliveryRecords(payload)
}

const handleShowDetail = async (row: SaleCountRecord) => {
    detailVisible.value = true
    detailLoading.value = true
    resetDetailData()

    const normalizedRow = normalizeSaleRecord(row)
    const fullRecord =
        rawRecords.value.find(item => item.saleOrderNo === row.saleOrderNo) || normalizedRow

    fillDetailBaseInfo(fullRecord)

    if (fullRecord && (fullRecord as any).details?.length) {
        detailGoods.value = (fullRecord as any).details
    } else {
        detailGoods.value = normalizeProductList(fullRecord)
    }

    detailExtras.attachments = normalizeAttachments(fullRecord)
    detailExtras.customFields = normalizeCustomFields(fullRecord)
    fillDetailLists(fullRecord)

    try {
        const outboundRecords = await fetchSaleDeliveryRecords(fullRecord.saleOrderNo || normalizedRow.saleOrderNo)
        if (outboundRecords.length) {
            detailLists.outbound = outboundRecords
        }
    } catch (error) {
        console.error('获取出库记录失败', error)
        ElMessage.warning('出库记录获取失败，展示已有数据')
    } finally {
        detailLoading.value = false
    }
}

const handleExport = async () => {
    try {
        const params = {
            salesOrderNo: queryForm.saleOrderNo || undefined,
            saleOrderNo: queryForm.saleOrderNo || undefined,
            customerName: queryForm.customerName || undefined,
            salesUser: queryForm.salesUser || undefined,
            salesDepartment: queryForm.salesDepartment || undefined,
            beginDate: queryForm.dateRange?.[0],
            endDate: queryForm.dateRange?.[1]
        }
        const res = await myaxios.get('/api/Statis/ExportSaleCount', {
            params,
            responseType: 'blob'
        })
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `销售统计_${moment().format('YYYYMMDDHHmmss')}.xlsx`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败', error)
        ElMessage.error('导出失败，请稍后重试')
    }
}

const getOrderIndex = (row: SaleCountRow) => {
    return (page.pageindex - 1) * page.pagesize + row.orderIndex + 1
}

const spanColumns = ['saleOrderNo', 'saleOrderDate', 'customerName', 'salesDepartment', 'salesUser']

const tableSpanMethod = ({ row, column }: { row: SaleCountRow, column: any }) => {
    if (column.label === '序号') {
        if (row.detailIndex === 0) {
            return { rowspan: row.detailCount, colspan: 1 }
        }
        return { rowspan: 0, colspan: 0 }
    }
    if (spanColumns.includes(column.property)) {
        if (row.detailIndex === 0) {
            return { rowspan: row.detailCount, colspan: 1 }
        }
        return { rowspan: 0, colspan: 0 }
    }
    return { rowspan: 1, colspan: 1 }
}

const formatAmount = (value?: number | string) => {
    const num = Number(value || 0)
    return num.toFixed(2)
}

const formatDate = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
    applyQuickRange(activeDateTab.value)
    fetchSaleCount()
})
</script>

<style scoped>
.sale-count-page {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.filter-card {
    margin-bottom: 16px;
}

.filter-form {
    margin-top: 16px;
}

.quick-tabs {
    display: flex;
    justify-content: space-between;
}

.stat-row {
    margin-bottom: 16px;
}

.stat-card {
    border-radius: 12px;
    background: #fff;
    transition: all 0.3s ease;
}

.stat-card .stat-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #86909c;
}

.stat-card .stat-value {
    font-size: 32px;
    font-weight: 600;
    margin: 8px 0;
}

.stat-card .stat-desc {
    font-size: 12px;
    color: #c0c4cc;
}

.amount-card .stat-value {
    color: #1677ff;
}

.customer-card .stat-value {
    color: #34c759;
}

.order-card .stat-value {
    color: #fa6400;
}

.table-card {
    border-radius: 12px;
}

.table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.toolbar-left .el-button {
    margin-right: 8px;
}

.toolbar-icon {
    margin-right: 4px;
}

.pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}

.detail-wrapper {
    padding: 12px 24px 24px;
}

.detail-header {
    margin-bottom: 16px;
}

.detail-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    font-weight: 600;
}

.detail-sub {
    margin-top: 8px;
    color: #86909c;
}

.detail-card {
    margin-bottom: 16px;
    border-radius: 12px;
}

.detail-card-title {
    font-weight: 600;
    margin-bottom: 12px;
}

.detail-summary {
    margin-top: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #606266;
}

.amount-text {
    color: #ff5722;
    font-weight: 600;
}

@media (max-width: 1200px) {
    .stat-row {
        display: block;
    }

    .stat-row .el-col {
        width: 100%;
        margin-bottom: 12px;
    }
}
</style>
